import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/paging/model/paging_params.dart';
import 'package:yt_devops/components/paging/page_state.dart';

import 'model/paging_datas.dart';

abstract class PagingController<M, S extends PagingState<M>>
    extends GetxController {
  /// PagingState
  late S pagingState;

  /// 刷新控件的 Controller
  RefreshController refreshController = RefreshController();

  /// 刷新控件的 Controller
  ScrollController scrollController = ScrollController();

  // bool loadLock = false;

  @override
  void onInit() {
    super.onInit();

    /// 保存 State
    pagingState = getState();

    /// 进入页面刷新数据
    refreshData();
  }

  @override
  void onReady() {
    super.onReady();
  }

  /// 刷新数据
  void refreshData({bool isSearch = false}) async {
    if (isSearch == true) {
      // if (pagingState.pageIndex != 1) {
      //   scrollController.animateTo(0,
      //       duration: const Duration(seconds: 1), curve: Curves.easeOut);
      // }
    }

    initPaging();
    await _loadData();
  }

  ///初始化分页数据
  void initPaging() {
    pagingState.pageIndex = 1;
    pagingState.hasMore = true;

    // update();
  }

  /// 数据加载
  Future<List<M>?> _loadData() async {
    // if (loadLock) {
    //   return [];
    // } else {
    //   loadLock = true;
    // }
    PagingParams pagingParams = PagingParams.create(
        pageIndex: pagingState.pageIndex, pageSize: pagingState.numberOnePage);
    PagingDatas<M>? pagingData = await loadData(pagingParams);

    /// 刷新完成
    refreshController.refreshCompleted();

    /// 加载完成
    refreshController.loadComplete();

    /// 数据为空，则没有更多数据
    List<M>? list = pagingData?.list;

    /// 数据不为空，则将数据添加到 data 中
    /// 并且分页页数 pageIndex + 1
    if (pagingState.pageIndex == 1) {
      pagingState.data.clear();
    }
    if (list != null && list.isNotEmpty) {
      pagingState.data.addAll(list);
      pagingState.pageIndex += 1;
    }

    /// 判断是否有更多数据
    pagingState.hasMore = pagingState.data.length < (pagingData?.total ?? 0);

    /// 判断是否有数据
    pagingState.isNoData = pagingState.data.isEmpty ? true : false;

    /// 更新界面
    update([pagingState.refreshId]);
    update();
    // loadLock = false;
    return list;
  }

  /// 加载更多
  void loadMoreData() async {
    await _loadData();

    /// 加载完成
    refreshController.loadComplete();
  }

  /// 最终加载数据的方法
  Future<PagingDatas<M>?> loadData(PagingParams pagingParams);

  /// 获取 State
  S getState();
}
